/* 
 * File:   RapidServer.h
 * Author: dell
 *
 * Created on 2012年4月2日, 下午1:45
 */

#ifndef RAPIDSERVER_H
#define	RAPIDSERVER_H

#include <evhttp/libev.h>
#include <unistd.h>
#include <string>
#include "common.h"
#include "config/ServerConfig.h"
#include "IHttpEngine.h"
#include "DynamicLib.h"
#include <evhttp/Process.h>
#include <evhttp/HttpServer.h>
#include <evhttp/Config.h>
#include "HttpServerEventListener.h"
#include "ProcessQuitSignal.h"
#include "FileCached.h"

namespace Rapid{
//    class RapidServer : protected Process, public ProcessQuitSignal{
    class RapidServer : protected Process{
    public:
        RapidServer(ServerConfig* serverConfig, std::string& hdir);
        virtual ~RapidServer();

        /**
         * 启动服务
         * @param daemon 指示是否以守护进程方式启动
         */
        virtual bool start(bool daemon, void* param=NULL);
        
        /** 停止服务，包括关闭子进程 */
        virtual void stop();
        
        int getServerPort();
        
        const char* getHomeDir(){
            return  homeDir.c_str();
        }
        
    public:
        HttpServer* httpServer;
        bool isDaemon;
        std::string homeDir; //服务主目录, 尾部有"/"
        FileCached fileCached;
    protected:
       /**
        * @see Process#run(void* param=NULL)
        */
        virtual int run(void* param=NULL);
        
        /*
         * @see IEventListener#handle(const Event* e)
         */
        virtual bool handle(const Event* e);
        
//        virtual bool onProcessSignalEvent(const ProcessSignalEvent* e);        
        
        virtual bool onProcessStartedEvent(const ProcessStartedEvent* e);
        
    private:
        void createHttpEngine();
        void destroyHttpEngine();
        bool startHttpServer(void* param);

   private:
        HttpServerEventListener httpServerEventListener;
        Config config;
    private:
//        ev::sig sigint; //SIGINT
//        void sigintCallback(ev::sig &ev, int revents);
   private:
//       void initSigev();
//       void startSigev();
//       void stopSigev();
//       void notifyChildren(); //通知子进程，退出系统, 向子进程发送退出系统命令
    private:
        DynamicLib httpEngineDynamicLib;
        ServerConfig* serverConfig;
        IHttpEngine* httpEngine;

        typedef IHttpEngine* (*HttpEngineCreate_t)(ServerConfig* serverConfig, const char* params);   //声明创建IHttpEngine的函数指针类型
        typedef void (*HttpEngineDestroy_t)(IHttpEngine*, const char* params);   //声明创建IHttpEngine的函数指针类型
    };
}
#endif	/* RAPIDSERVER_H */

